import Dexie, { Table } from 'dexie';
import PositionedSentence from './model/PositionedSentence';

class SentenceStorage extends Dexie {
  sentences!: Table<PositionedSentence, string>;
  constructor() {
    super('SentencesDB');
    this.version(1).stores({
      sentences: 'remark',
    });
  }

  async addSentence(sentence: PositionedSentence): Promise<void> {
    await this.transaction('rw', this.sentences, async () => {
      await this.sentences.add(sentence, sentence.remark);
    });
  }

  async searchSentences(prefix: string) {
    return await this.sentences.where('remark').startsWithIgnoreCase(prefix).reverse().sortBy('createTime');
  }

  async deleteByRemark(remark: string) {
    await this.sentences.delete(remark);
  }
}

export const sentenceDB = new SentenceStorage();
